<route lang="json5">
{
  style: {
    navigationBarTitleText: '登录',
  },
}
</route>

<template>
  <view class="login-container">
    <view class="logo-container">
      <image class="logo" src="/static/logo.png" mode="aspectFit" />
      <text class="app-name">助学堂</text>
    </view>

    <view class="form-container">
      <wd-cell-group>
        <wd-input
          v-model="form.phone"
          label="手机号"
          placeholder="请输入手机号"
          type="number"
          maxlength="11"
          :error="errors.phone"
          :error-message="errors.phoneMessage"
          @blur="validatePhone"
        >
          <template #prefix>
            <text class="iconfont icon-phone"></text>
          </template>
        </wd-input>

        <wd-input
          v-model="form.password"
          label="密码"
          placeholder="请输入密码"
          :type="showPassword ? 'text' : 'password'"
          :error="errors.password"
          :error-message="errors.passwordMessage"
          @blur="validatePassword"
        >
          <template #prefix>
            <text class="iconfont icon-lock"></text>
          </template>
          <template #suffix>
            <text
              class="iconfont"
              :class="showPassword ? 'icon-eye' : 'icon-eye-close'"
              @click="togglePasswordVisibility"
            ></text>
          </template>
        </wd-input>
      </wd-cell-group>

      <view class="options-container">
        <view class="remember-container">
          <wd-checkbox v-model="form.remember">记住密码</wd-checkbox>
        </view>
        <text class="forgot-password" @click="navigateToForgotPassword">忘记密码？</text>
      </view>

      <view class="button-container">
        <wd-button type="primary" block @click="handleLogin" :loading="loading">
          登录
        </wd-button>
      </view>

      <view class="register-container">
        <text>还没有账号？</text>
        <text class="register-link" @click="navigateToRegister">立即注册</text>
      </view>

      <view class="divider">
        <text class="divider-text">其他登录方式</text>
      </view>

      <view class="social-login">
        <view class="social-item" @click="handleSocialLogin('wechat')">
          <text class="iconfont icon-wechat"></text>
          <text>微信</text>
        </view>
        <view class="social-item" @click="handleSocialLogin('qq')">
          <text class="iconfont icon-qq"></text>
          <text>QQ</text>
        </view>
      </view>
    </view>

    <!-- 登录协议 -->
    <view class="agreement">
      <wd-checkbox v-model="form.agreement" @change="handleAgreementChange">
        我已阅读并同意
      </wd-checkbox>
      <text class="link" @click="showUserAgreement">《用户协议》</text>
      <text>和</text>
      <text class="link" @click="showPrivacyPolicy">《隐私政策》</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { showToast } from '@/utils/toast'
import { login, thirdPartyLogin } from '@/api/auth'
import { setToken, setUserInfo } from '@/utils/auth'

const form = reactive({
  phone: '',
  password: '',
  remember: false,
  agreement: false,
})

const errors = reactive({
  phone: false,
  phoneMessage: '',
  password: false,
  passwordMessage: '',
})

const loading = ref(false)
const showPassword = ref(false)

// 表单验证
const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!form.phone) {
    errors.phone = true
    errors.phoneMessage = '请输入手机号'
    return false
  }
  if (!phoneRegex.test(form.phone)) {
    errors.phone = true
    errors.phoneMessage = '请输入正确的手机号'
    return false
  }
  errors.phone = false
  errors.phoneMessage = ''
  return true
}

const validatePassword = () => {
  if (!form.password) {
    errors.password = true
    errors.passwordMessage = '请输入密码'
    return false
  }
  if (form.password.length < 6) {
    errors.password = true
    errors.passwordMessage = '密码长度不能小于6位'
    return false
  }
  errors.password = false
  errors.passwordMessage = ''
  return true
}

const validateForm = () => {
  return validatePhone() && validatePassword()
}

// 处理登录
const handleLogin = async () => {
  if (!form.agreement) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    const result = await login({
      phone: form.phone,
      password: form.password,
      remember: form.remember
    })
    
    // 保存token和用户信息
    setToken(result.token)
    setUserInfo(result.userInfo)
    
    showToast('登录成功')
    uni.switchTab({
      url: '/pages/index/index',
    })
  } catch (error) {
    showToast(error.message || '登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理第三方登录
const handleSocialLogin = async (platform: 'wechat' | 'qq') => {
  if (!form.agreement) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  try {
    // 获取第三方登录code
    const [err, res] = await uni.login({
      provider: platform
    })

    if (err) {
      throw new Error(err.errMsg)
    }

    loading.value = true
    const result = await thirdPartyLogin(platform, res.code)
    
    // 保存token和用户信息
    setToken(result.token)
    setUserInfo(result.userInfo)
    
    showToast('登录成功')
    uni.switchTab({
      url: '/pages/index/index',
    })
  } catch (error) {
    showToast(error.message || '第三方登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 处理协议变更
const handleAgreementChange = (value: boolean) => {
  form.agreement = value
}

// 页面跳转
const navigateToRegister = () => {
  uni.navigateTo({
    url: '/pages/login/register',
  })
}

const navigateToForgotPassword = () => {
  uni.navigateTo({
    url: '/pages/login/forgot-password',
  })
}

// 显示协议
const showUserAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/user',
  })
}

const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacy',
  })
}
</script>

<style lang="scss">
.login-container {
  min-height: 100vh;
  padding: 40px 30px;
  background-color: #fff;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40px;

  .logo {
    width: 120px;
    height: 120px;
    margin-bottom: 16px;
  }

  .app-name {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }
}

.form-container {
  margin-bottom: 20px;
}

.options-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 0;

  .forgot-password {
    color: #666;
    font-size: 14px;
  }
}

.button-container {
  margin: 24px 0;
}

.register-container {
  text-align: center;
  margin: 16px 0;
  font-size: 14px;

  .register-link {
    color: #4a90e2;
    margin-left: 4px;
  }
}

.divider {
  display: flex;
  align-items: center;
  margin: 24px 0;

  &::before,
  &::after {
    content: '';
    flex: 1;
    height: 1px;
    background-color: #eee;
  }

  .divider-text {
    padding: 0 16px;
    color: #999;
    font-size: 14px;
  }
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-top: 24px;

  .social-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    color: #666;

    .iconfont {
      font-size: 32px;
    }

    text {
      font-size: 14px;
    }
  }
}

.agreement {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 40px;
  text-align: center;
  font-size: 12px;
  color: #666;
  padding: 0 30px;

  .link {
    color: #4a90e2;
  }
}
</style>
